"use client";

import { type TDateElement } from "platejs";
import { type PlateElementProps } from "platejs/react";

import { PlateElement, useReadOnly } from "platejs/react";

import { Calendar } from "@/components/plate/ui/calendar";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/plate/ui/popover";
import { cn } from "@/lib/utils";

export function DateElement(props: PlateElementProps&lt;TDateElement&gt;) {
  const { editor, element } = props;

  const readOnly = useReadOnly();

  const trigger = (
    <span>
      {element.date ? (
        (() =&gt; {
          const today = new Date();
          const elementDate = new Date(element.date);
          const isToday =
            elementDate.getDate() === today.getDate() &&
            elementDate.getMonth() === today.getMonth() &&
            elementDate.getFullYear() === today.getFullYear();

          const isYesterday =
            new Date(today.setDate(today.getDate() - 1)).toDateString() ===
            elementDate.toDateString();
          const isTomorrow =
            new Date(today.setDate(today.getDate() + 2)).toDateString() ===
            elementDate.toDateString();

          if (isToday) return "Today";
          if (isYesterday) return "Yesterday";
          if (isTomorrow) return "Tomorrow";

          return elementDate.toLocaleDateString(undefined, {
            day: "numeric",
            month: "long",
            year: "numeric",
          });
        })()
      ) : (
        <span>Pick a date</span>
      )}
    </span>
  );

  if (readOnly) {
    return trigger;
  }

  return (
    &lt;PlateElement
      {...props}
      className="inline-block"
      attributes={{
        ...props.attributes,
        contentEditable: false,
      }}
    &gt;
      &lt;Popover&gt;
        &lt;PopoverTrigger asChild&gt;{trigger}&lt;/PopoverTrigger&gt;
        &lt;PopoverContent className="w-auto p-0"&gt;
          &lt;Calendar
            selected={new Date(element.date as string)}
            onSelect={(date) =&gt; {
              if (!date) return;

              editor.tf.setNodes(
                { date: date.toDateString() },
                { at: element },
              );
            }}
            mode="single"
            initialFocus
          /&gt;
        &lt;/PopoverContent&gt;
      &lt;/Popover&gt;
      {props.children}
    &lt;/PlateElement&gt;
  );
}
